<?php
namespace App\Extend\Wx;

use App\Server\CurlApi;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

class  Wxlogin
{
    /**
     * 微信获取openid
     * @Author abell
     * @DateTime 2020-05-28
     * @param string $code
     * @return array
     */
    public  function getOpenId($code=''){
        $appid = config('web.wx_account.appid');
        $appsecret = config('web.wx_account.appsecret');
        $appsecret = trim($appsecret);
        $url = "/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $config = ['timeout'=>10,'base_uri' => 'https://api.weixin.qq.com'];
        $curl = make(CurlApi::class,compact('config'));
        $data = $curl->get($url);
        if($data['errorCode']){
            return [400,'Error','登录失败'];
        }else{
            return [0,'ok',$data['data']];
        }
    }

    /**
     * 获取微信登录token
     * @Author abell
     * @DateTime 2020-05-28
     * @return array
     */
    public function getToken(){
        $appid = config('web.wx_account.appid');
        $appsecret = config('web.wx_account.appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $config = ['timeout'=>30,'base_uri' => 'http://www.baidu.com'];
        // 获取token写入数据库
        $res_json = make(CurlApi::class,compact('config'))->get($url);
        if(array_key_exists('data',$res_json)){
            // 判断返回值是否有data
            $res_data_array = json_decode($res_json['data'],true);
            if(array_key_exists('errcode',$res_data_array)){
                // 登录错误
                return ['code'=>400,'data' => $res_data_array];
            }else{
                // 获取成功
                return ['code'=>0,'data'=>$res_json['data']];
            }
        }else{return ['code'=>401,'data' => 'Error'];}
    }

    /**
     * token存redis数据
     * @Author abell
     * @DateTime 2020-05-28
     * @param bool $force_update 是否强制更新token
     * @return array
     */
    public function check_token_redis($force_update=false){
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        if($force_update){
            return  $this->save_token_redis();
        }else{ // 查看token是否存在
            $exists = $redis->get('wechat_access_token');
            if($exists){
                // 判断token是否过期
                if($redis->get('wechat_over_time') > time()){
                    return  $redis->get('wechat_access_token');
                }else{// token过期,需要重新获取,覆盖写入
                    return  $this->save_token_redis();}
            }else{// 获取token写入redis
                return  $this->save_token_redis();}}
    }

    /**
     * 保存token到redis,获取最新的token
     * @Author abell
     * @DateTime 2020-05-28
     * @return array
     */
    private function save_token_redis(){
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $get_token = self::getToken();
        $data_array = json_decode($get_token['data'],true);
        $redis->set('wechat_access_token',$data_array['access_token']);
        $redis->set('wechat_over_time',time() + (int)$data_array['expires_in']);
        $redis->set('wechat_expires_in',$data_array['expires_in']);
        return  $redis->get('wechat_access_token');
    }
}